package cn.hd01.web.controller;

import java.math.BigDecimal;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.DistributorLevel;
import cn.hd01.service.CustomerService;
import cn.hd01.service.DistributorLevelService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.util.WebException;

@Controller
@RequestMapping("/distributorLevel")
@Auth
public class DistributorLevelController {
	
	@Autowired
	private DistributorLevelService distributorLevelService;
	
	@Autowired
	private CustomerService customerService;
	
	@RequestMapping(method = RequestMethod.GET)
	public String index(Model m, HttpServletRequest request) {
		return "distributorLevel";
	}

	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	private Page<DistributorLevel> find(DistributorLevel dl, @PageableDefault Pageable pageable) {
		return distributorLevelService.findAll(dl, pageable); 
	}

	@ResponseBody
	@RequestMapping(path = "/delete/{id}", method = RequestMethod.GET)
	private void delete(@PathVariable("id") Integer id) {
		customerService.updateCustomerLevel(id);
		distributorLevelService.delete(id);
	}

	@ResponseBody
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	private void save(DistributorLevel level) {

		validateLevel(level);
		
		if(level.getId() == null){//保存
			
			Date date = new Date();
			level.setCreateTime(date);
			level.setUpdateTime(date);
			distributorLevelService.save(level);
			
		}else {//更新
			distributorLevelService.updateDistributorLevel(level);
		}
	}
	
	private void validateLevel(DistributorLevel level){
		
		if(StringUtils.isEmpty(level.getLevelName())){
			throw new WebException(HttpStatus.BAD_REQUEST, "名字不能为空");
		}
		
		if(level.getRebateRate() == null || level.getRebateRate().compareTo(BigDecimal.ZERO) < 0){
			throw new WebException(HttpStatus.BAD_REQUEST, "提成不能为空或者负数");
		}
		
	}
}
